<template>
	<view>
		<view v-if="playUrl">
			<uni-video :playUrl="playUrl" style="width:100%; height: 225px;"></uni-video>
			<button class="cu-btn block" size="mini" :style="[{backgroundColor:themeConfig.primaryColor}]"
				style="color: #fff" @tap="playUrl = null">{{$t('close')}}</button>
		</view>
		<view v-for="(sensor,sensorIndex) in sensorWithSetting" :key="sensorIndex">
			<view v-if="sensor.settingList.length != 0" class="text-grey text-lg">
				<view class="action margin-bottom-sm flex justify-between" @click="tapSensor(sensor)">
					<view>
						<text class="cuIcon-titles text-green"></text>
						<text
							class="text-bold margin-right-sm">{{formatSensorType(sensor.type)}}{{$t('port')}}:{{sensor.port}}</text>
						<text v-if="sensor.sensorName">| {{sensor.sensorName}}</text>
					</view>
					<text v-if="showGoToSensor" class="cuIcon-right text-black text-xl margin-top-xs"
						style="float: right;"></text>
				</view>
				<view
					style="display: grid;grid-template-columns:1fr 1fr;grid-template-rows 1fr 1fr;grid-column-gap: 5px;">
					<view v-for="(item,index) in sensor.settingList" :key="index"
						:style="(item.isFullLine || !showGoToSensor ? 'grid-column-start: span 2':'grid-column-start: span 1')">
						<view :style="{'background': item.background}"
							class="bg-white padding-sm margin-bottom-sm common-box">
							<view class="flex justify-start margin-bottom">
								<view class="cu-avatar radius sm" :style="[{backgroundImage:`url(${item.iconUrl})`}]"
									style="width: 55rpx;height: 55rpx;background-color:rgba(0,0,0,0);;margin: 5rpx 8rpx 0 0;">
								</view>
								<view>
									<view class="text-sm text-bold text-grey text-left">
										<text v-if="item.remark && item.remark!==''">
											{{item.remark}}
										</text>
										<text v-else>
											{{item.name}}
										</text>
									</view>
									<view class="text-gray text-xs">
										{{formatDateTime(item.updateDate)}}
									</view>
								</view>
							</view>
							<view class="margin-bottom" style="min-height: 20px;">
								<view v-if="item.type==='fixedParam' && item.paramList.length > 0">
									<!-- 固定参数 -->
									<view class="flex justify-end flex-wrap">
										<button v-for="(param,paramIndex) in item.paramList" :key="paramIndex"
											:disabled="item.disabled"
											class="margin-right-sm margin-bottom-sm cu-btn block" size="mini"
											:class="[item.value == param.value ? 'selectButton' : 'noSelectButton']"
											:style="{'--color': themeConfig.primaryColor}" @tap="changeParam"
											:data-keyName="item.keyName" :data-port="item.port"
											:data-value="param.value"
											data-type="fixed">{{param.name + item.unit}}</button>

									</view>
								</view>
								<view v-else-if="item.type==='switch'">
									<!-- 开关量 -->
									<view class="flex justify-end">
										<switch :class="[themeConfig.theme,item.value?'checked':'']" class="sm radius"
											:disabled="item.disabled" :checked="item.value" @change="changeParam"
											:data-keyName="item.keyName" :data-port="item.port" data-type='switch'>
										</switch>
									</view>
								</view>
								<view v-else-if="item.type==='time'">
									<!-- 定时设置 -->
									<view class='flex justify-end'>
										<picker :disabled="item.disabled" mode="time" :value="item.value"
											@change="changeParam" :data-keyName="item.keyName" :data-port="item.port"
											data-type='time' :style="{'--color': themeConfig.primaryColor}"
											class="cu-btn block selectButton setting-border"
											>
											<view style="color: #FFF">
												<text class="cuIcon-time margin-right-sm" />
												<text>{{item.value}}</text>
											</view>
										</picker>
									</view>
								</view>
								<view v-else-if="item.type==='timeSlot'">
									<!-- 时间段设置 -->
									<view class='flex justify-end'>
										<picker :disabled="item.disabled" mode="multiSelector" @change="changeParam"
											:data-keyName="item.keyName" :data-port="item.port" data-type='timeSlot'
											:value="item.timeSlotMultiIndex" :range="timeSlotMultiArray"
											:style="{'--color': themeConfig.primaryColor}"
											class="cu-btn block selectButton setting-border">
											<view style="color: #FFF">
												<text class="cuIcon-time margin-right-sm" />
												<text>{{item.value}}</text>
											</view>
										</picker>
									</view>
								</view>
								<view v-else-if="item.type==='noParam'">
									<!-- 无参数命令 -->
									<view class='flex justify-end'>
										<button :disabled="item.disabled" class="cu-btn block" size="mini"
											:style="[{backgroundColor:themeConfig.primaryColor}]" style="color: #fff"
											@tap="changeParam" :data-keyName="item.keyName" :data-port="item.port"
											data-type='noParam'>{{$t('confirm')}}</button>
									</view>
								</view>
								<view v-else-if="item.type==='slider'">
									<!-- 拖动条 -->
									<view class='flex justify-end' style="margin-left:120rpx">
										<slider :disabled="item.disabled" class="flex-sub" show-value max="100" min="0"
											step="1" :value="item.value" :activeColor="themeConfig.primaryColor"
											block-size="20" @change="changeParam" :data-keyName="item.keyName"
											:data-port="item.port" data-type="slider"></slider>
									</view>
								</view>
								<view v-else-if="item.type==='video'">
									<!-- 其他 -->
									<form @submit="changeParam" :data-keyName="item.keyName" :data-port="item.port"
										:data-type="item.type">
										<view class="flex align-center justify-end ">
											<input :disabled="item.disabled"
												class="margin-right-sm ztnCustom-custominput flex-sub setting-border"
												style="color: #8799a3"
												type='text' name="custom" :value="item.value" />
											<text class='text-orange margin-right-sm'
												v-if="item.unit">{{item.unit}}</text>
											<button :disabled="item.disabled" class="cu-btn block" size="mini"
												:style="{backgroundColor:themeConfig.primaryColor}" style="color: #fff;"
												hover-class="btn-hover-class" form-type="submit">{{$t('play')}}</button>
										</view>
									</form>
								</view>
								<view v-else-if="item.type==='multiCustom'">
									<!-- 富自定义 -->
									<form @submit="changeParam" :data-keyName="item.keyName" :data-port="item.port"
										data-type="multiCustom">
										<view class="flex justify-end flex-wrap ">
											<view v-for="(param,paramIndex) in item.valueList" :key="paramIndex"
												class="margin-right-sm margin-bottom-sm">
												<view v-if="param.type==='fixedParam'">
													<!-- 固定参数 -->
													<picker :disabled="item.disabled"
														@change="multiCustomFixedParamChange($event,item,param)"
														:value="param.valueIndex" :range="item.paramList"
														range-key="name">
														<view class="picker ztnCustom-custominput setting-border"
															style="color: #8799a3;width: 120px;">
															{{item.paramList[param.valueIndex]['name'] + item.unit}}
														</view>
													</picker>
												</view>
												<view v-else-if="param.type==='switch'">
													<!-- 开关量 -->
													<switch :class="themeConfig.theme"
														class="sm ztnCustom-custominput radius"
														:disabled="item.disabled" :checked="param.value">
													</switch>
												</view>
												<view v-else-if="param.type==='time'">
													<!-- 定时设置 -->
													<picker :disabled="item.disabled" class="flex-sub" mode="time"
														:value="item.value"
														@change="multiCustomTimeChange($event,param)">
														<view class="ztnCustom-custominput setting-border"
															style="color: #8799a3;width: 120px;">
															{{param.value}}
														</view>
													</picker>
												</view>
												<view v-else-if="param.type==='timeSlot'">
													<!-- 时间段设置 -->
													<picker :disabled="item.disabled" class="flex-sub"
														mode="multiSelector" :value="param.timeSlotMultiIndex"
														:range="timeSlotMultiArray"
														@change="multiCustomTimeSlotChange($event,param)">
														<view class="ztnCustom-custominput setting-border"
															style="color: #8799a3;width: 120px">
															{{param.value}}
														</view>
													</picker>
												</view>
												<view v-else-if="param.type==='slider'">
													<!-- 拖动条 -->
													<slider style="width: 150px;" :disabled="item.disabled"
														@change="multiCustomSliderChange($event,param)" class="flex-sub"
														show-value max="100" min="0" step="1" :value="param.value"
														:activeColor="themeConfig.primaryColor" block-size="20">
													</slider>
												</view>
												<view v-else-if="param.type==='video'">
													<input :disabled="item.disabled" class="ztnCustom-custominput setting-border"
														style="width: 120px;color: #8799a3"
														type='text' name="custom" v-model="param.value" />
													<text class='text-orange margin-right-sm'
														v-if="item.unit &&item.unit!==''">{{item.unit}}</text>
												</view>
												<view v-else>
													<input :disabled="item.disabled" class="ztnCustom-custominput setting-border"
														style="color: #8799a3"
														type='text' name="custom" v-model="param.value" />
													<text class='text-orange margin-right-sm'
														v-if="item.unit &&item.unit!==''">{{item.unit}}</text>
												</view>
											</view>
											<button :disabled="item.disabled" class="cu-btn block" size="mini"
												:style="[{backgroundColor:themeConfig.primaryColor}]"
												style="color: #fff;" hover-class="btn-hover-class"
												form-type="submit">{{$t('confirm')}}</button>
										</view>
									</form>
								</view>
								<view v-else>
									<!-- 其他 -->
									<form @submit="changeParam" :data-keyName="item.keyName" :data-port="item.port"
										:data-type="item.type">
										<view class="flex align-center justify-end ">
											<input :disabled="item.disabled"
												class=" margin-right-sm ztnCustom-custominput flex-sub setting-border"
												style="color: #8799a3"
												type='text' name="custom" :value="item.value" />
											<text class='text-orange margin-right-sm'
												v-if="item.unit">{{item.unit}}</text>
											<button :disabled="item.disabled" class="cu-btn block" size="mini"
												:style="{backgroundColor:themeConfig.primaryColor}" style="color: #fff;"
												hover-class="btn-hover-class"
												form-type="submit">{{$t('confirm')}}</button>
										</view>
									</form>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>


		<view class="cu-modal bottom-modal" :class="showErrorModal?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<view class="action text-blue" @tap="hideErrorModal">{{$t('close')}}</view>
				</view>
				<view class="padding-xl">
					{{settingError}}
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		showToast,
		showLoading,
		hideLoading
	} from '@/util/toast.js'
	import {
		formatSensorType
	} from '@/util/dataUtil.js'
	import {
		formatSettingList
	} from '@/util/utils.js'
	import *
	as iotDeviceSettingApi from '@/api/iot/iotDeviceSettingApi.js'
	import *
	as deviceSensorApi from '@/api/iot/iotDeviceSensorApi.js'
	import UniVideo from '@/components/ztn-custom/UniVideo/index.vue'
	import * as storage from '@/util/storage.js'
	import {
		formatDateTime
	} from '@/util/formatTime.js'
	const hours = [];
	const minutes = [];
	const thours = [];
	const tminutes = [];
	for (let i = 0; i < 24; i++) {
		let n = i + ''
		hours[i] = n[1] ? n : '0' + n
	}
	for (let i = 0; i < 60; i++) {
		let n = i + ''
		minutes[i] = n[1] ? n : '0' + n
	}
	for (let i = 0; i < 24; i++) {
		let n = i + ''
		thours[i] = n[1] ? n : '0' + n
	}
	for (let i = 0; i < 60; i++) {
		let n = i + ''
		tminutes[i] = n[1] ? n : '0' + n
	}

	export default {
		name: 'Setting',
		data() {
			return {
				// 控制
				sensorWithSetting: [],
				timeSlotMultiArray: [hours, minutes, thours, tminutes],
				// timeSlotMultiIndex: [0, 0, 0, 0],
				settingError: '',
				showErrorModal: false,
				showHidden: storage.getShowHidden(),
				playUrl: null,
				setting: {}
			}
		},
		props: {
			deviceName: {
				type: String,
				default: ''
			},
			deviceCore: {
				type: String,
				default: ''
			},
			showGoToSensor: {
				type: Boolean,
				default: true
			}
		},
		computed: {
			themeConfig() {
				return this.$store.state.themeConfig
			}
		},
		components: {
			UniVideo
		},
		mounted() {
			this.init()
			storage.setDeviceNavigationComponent('deviceSetting')
		},
		methods: {
			formatDateTime(time) {
				return formatDateTime(time, this.$t('unKnow'))
			},
			formatSensorType(type) {
				return formatSensorType(this, type)
			},
			tapSensor(e) {
				let {
					sensorId,
					sensorName,
					port
				} = e
				uni.navigateTo({
					url: `/pages/deviceSensorData/deviceSensorData?sensorId=${sensorId}&sensorName=${sensorName}&deviceCore=${this.deviceCore}&deviceName=${this.deviceName}&port=${port}`
				})
			},
			init() {
				this.getListWith()
			},
			getListWith() {
				const withExplain = false
				const withParam = false
				const withSetting = true
				deviceSensorApi.getListWith({
					deviceCore: this.deviceCore,
					withExplain: withExplain,
					withParam: withParam,
					withSetting: withSetting,
				}).then((res) => {
					const {
						data
					} = res
					if (data) {
						const sensorWithSetting = []
						data.forEach(sensor => {
							if (this.showHidden || !sensor.hidden) {
								if (!sensor.settingList) {
									return
								}
								const settingList = []
								sensor.settingList.forEach(setting => {
									if (this.showHidden || !setting.hidden) {
										settingList.push(setting)
									}
								})
								sensor.settingList = formatSettingList(settingList)
								if (sensor.settingList.length > 0) {
									sensorWithSetting.push(sensor)
								}
							}
						})
						this.sensorWithSetting = sensorWithSetting
					}
				})
			},
			multiCustomFixedParamChange(e, item, param) {
				param.valueIndex = e.detail.value
				param.value = item.paramList[e.detail.value].value
			},
			multiCustomTimeChange(e, param) {
				param.value = e.detail.value
			},
			multiCustomSliderChange(e, param) {
				param.value = e.detail.value
			},
			multiCustomTimeSlotChange(e, param) {
				let index = e.detail.value;
				let hour = this.timeSlotMultiArray[0][index[0]]
				let minute = this.timeSlotMultiArray[1][index[1]]
				let thour = this.timeSlotMultiArray[2][index[2]]
				let tminute = this.timeSlotMultiArray[3][index[3]]
				let timeSlot = hour + ':' + minute + ' / ' + thour + ':' + tminute
				param.value = timeSlot
			},
			changeParam(e) {
				const data = e.currentTarget.dataset
				this.setting = {
					keyName: data.keyname,
					port: data.port,
					value: data.value,
					type: data.type,
				}
				switch (this.setting.type) {
					case 'fixed':
						this.setting.value = data.value
						this.sendSetting()
						break;
					case 'switch':
						this.setting.value = e.detail.value ? '1' : '0'
						this.sendSetting()
						break;
					case 'time':
						this.setting.value = e.detail.value
						this.sendSetting()
						break;
					case 'timeSlot':
						const index = e.detail.value;
						const hour = this.timeSlotMultiArray[0][index[0]]
						const minute = this.timeSlotMultiArray[1][index[1]]
						const thour = this.timeSlotMultiArray[2][index[2]]
						const tminute = this.timeSlotMultiArray[3][index[3]]
						this.setting.value = hour + ':' + minute + ' / ' + thour + ':' + tminute
						this.sendSetting()
						break;
					case 'noParam':
						this.sendSetting()
						break;
					case 'slider':
						this.setting.value = e.detail.value
						this.sendSetting()
						break;
					case 'multiCustom':
						let multiCustomSetting
						for (const sensor of this.sensorWithSetting) {
							if (sensor.port === this.setting.port) {
								for (const setting of sensor.settingList) {
									if (setting.keyName === this.setting.keyName) {
										multiCustomSetting = setting
									}
								}
							}
						}
						const value = []
						multiCustomSetting.valueList.forEach(p => {
							if (p.type === 'switch') {
								value.push(p.value ? '1' : '0')
							} else {
								value.push(p.value)
							}

						})
						this.setting.value = value
						this.sendSetting()
						break
					default:
						this.setting.value = e.detail.value.custom
						this.sendSetting()
				}
			},
			sendSetting() {
				showLoading(this.$t('loading'), true)
				iotDeviceSettingApi.sendSetting({
					deviceCore: this.deviceCore,
					value: this.setting.value,
					keyName: this.setting.keyName,
					port: this.setting.port
				}).then((
					res) => {
					const {
						data,
						msg
					} = res
					if (data) {
						showToast(this.$t('success'), 'none', 1000, true)
						if (this.setting.type === 'video') {
							this.playUrl = data.setting.value
						}
					} else {
						this.showErrorModal = true
						this.settingError = msg
					}
					hideLoading()
					this.init()
				})
			},
			hideErrorModal() {
				this.showErrorModal = false
			},
		},
	}
</script>
<style scoped>
	
	.ztnCustom-custominput {
		text-align: center;
		height: 64rpx;
		line-height: 64rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		padding: 0 1.34em;
	}

	.selectButton {
		color: #fff;
		background-color: var(--color)
	}

	.noSelectButton {
		color: #8799a3;
		background-color: #efefef
	}
</style>
